package admin

import (
	"errors"

	"github.com/casbin/casbin/v2"
	"github.com/casbin/casbin/v2/model"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

func InitCasbin(db *gorm.DB) *casbin.Enforcer {
	a, _ := gormadapter.NewAdapterByDB(db)
	m, _ := model.NewModelFromString(`
	[request_definition]
	r = sub, obj, act

	[policy_definition]
	p = sub, obj, act

	[role_definition]
	g = _, _

	[policy_effect]
	e = some(where (p.eft == allow))

	[matchers]
	m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
	`)
	e, _ := casbin.NewEnforcer(m, a)
	e.LoadPolicy()
	e.EnableAutoSave(true)
	return e
}

func HashPassword(pwd string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	return string(hash), err
}

func LoginCheck(username, pwd string) (*LoginInfo, error) {
	info := &LoginInfo{}
	Instance.DB.Table("Users").Where("Username = ?", username).First(&info)
	if info.ID == 0 {
		return nil, errors.New("用户名或密码错误")
	}
	err := bcrypt.CompareHashAndPassword([]byte(info.Password), []byte(pwd))
	if err != nil {
		return nil, errors.New("用户名或密码错误")
	}
	err = GenerateToken(info)

	return info, err
}
